package py.com.fms.fms.session.maintenances;

//External classes imports 
//Java Classes
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

//Seam Classes
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

//project classes imports
import py.com.fms.fms.bean.EmployeeBean;
import py.com.fms.fms.bean.EnterpriseBean;
import py.com.fms.fms.bean.PersonBean;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.persistence.services.EmployeeServices;
import py.com.fms.fms.persistence.services.EnterpriseServices;
import py.com.fms.fms.persistence.services.PersonServices;
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.exception.CommonException;
import py.com.fms.session.ParamHolder;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.utilities.*;

@SuppressWarnings("unused")
@Name("editEmp")
@Scope(ScopeType.SESSION)
public class EditEmployee {
	
	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private boolean editMode;
	private String initVar;
	private Date today = null;
	
	// Task Attendees Attributes 
	
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{paramHolder}")
	private ParamHolder param;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In Credentials credentials;
	@In Identity identity;
	private UsersBean user;
	
	private DateAssistant dateAssist;

	// Attribute used for saving and deleting
	private EmployeeBean employee;
	
	// Services
	private EmployeeServices emSrv;
	private PersonServices prSrv;
	private UsersServices usSrv;
	
	// Collection of monedasBean
	private Collection<EmployeeBean> allEmployees;

	// Attribute used for editing or updating
	private EmployeeBean editEmployee;
	
//	Necessary Attributes;
	private PersonBean personCod;
	private PersonBean personData;
	private Long personId;


	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 * @throws CommonException 
	 */

	// Used to initialize information from a variable
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			this.initBeans();
			this.initServices();
			this.initAssistants();
			this.initCollections();
			this.loadDataGrid();
			this.loadParams();
			
			if(credentials != null){
				System.out.println("Credenciales Encontradas");
				this.getUser().setUserName(credentials.getUsername());
				System.out.println("User Name: " + this.getUser().getUserName());
				user = usSrv.getUserDataByName(this.getUser().getUserName());
				this.setUser(user);
				System.out.println("User: " + this.getUser());
			}else{	
				System.out.println("Credenciales Nulas");
			}
		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	
	public void loadParams() throws CommonException{
		this.param.initData();
		this.param.loadParams();
	}
	
	public void initBeans(){
		
		if (employee == null){
			employee = new EmployeeBean();
			employee.setStatus(true);
		}
		
		if (editEmployee == null){
			editEmployee = new EmployeeBean();
		}
		if (personCod == null){
			personCod = new PersonBean();
		}
		if (personData == null){
			personData = new PersonBean();
		}
		if (user == null){
			user = new UsersBean();
		}
	}
	
	public void initServices() throws CommonException{
		
		if (emSrv == null){
			emSrv = new EmployeeServices(this.sqlMap.getConfig());
		}
		
		if (prSrv == null){
			prSrv = new PersonServices(this.sqlMap.getConfig());
		}
		
		if (usSrv == null){
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		
				
	}
	
	public void initAssistants(){
		
		
		if(aid == null){
			aid = new WithinHolder();
		}
		
		if(param == null){
			param = new ParamHolder();
		}
		
		if(convert == null){
			convert = new ConvertAssistant();
		}
		
		if(dateAssist == null){
			dateAssist = new DateAssistant();
		}
		
	}
	
	public void initCollections(){
		if(allEmployees == null){
			allEmployees = new ArrayList<EmployeeBean>();
		}
		
	

	}
	
	public void cleanData(){
		
		employee = null;
		editEmployee = null;
		personCod = null;
		personData = null;
		user = null;
		emSrv = null;
		prSrv = null;
		usSrv = null;
		aid = null;
		param = null;
		convert = null;
		dateAssist = null;
		allEmployees = null;

		
	}

	// Used to load a grid using a collection
	private void loadDataGrid() {
		try {
			this.setAllEmployees(emSrv.getAllEmployees());
			for (EmployeeBean employee : this.getAllEmployees()) {
				System.out.println(employee.getCod());
			}
		} catch (CommonException e) {
			e.printStackTrace();
		}
	}

	// Used to cancel
	public String cancelData() {
//		this.facesMessages.clear();
		this.setInitVar("S");
		return null;
	}
		

	// Used for data saving process
	public String saveNewData() throws ParseException {
		try {
//			this.facesMessages.clear();
			EmployeeBean newEmp = new EmployeeBean();
			aid = new WithinHolder();
			this.today = DateAssistant.getHoleDateTime();
			personId = convert.getPersonId(this.getPersonCod());
			personData = convert.getPersonData(this.getPersonCod());
			
			if(this.getPersonId() == null){
				System.out.println("Person id is null");
			}else{
				System.out.println("Person id:" + this.personId);
			}		

			if (this.getEmployee() == null) {
				System.out.println("this.getEmployee() == null");
				throw new CommonException("error.fms.menu.error.countrynotexist");
			}
			System.out.println("BEFORE SETTING VALUES");
			// Setting field values
			newEmp.setCod(convert.convertField(this.getEmployee().getCod()));
			newEmp.setIdPerson(this.getPersonId());
			newEmp.setIdEnt(param.getEnt().getId());
			newEmp.setStatus(this.getEmployee().getStatus());
			newEmp.setStartDate(this.today);
			newEmp.setLastUpdDate(this.today);
			System.out.println(this.today);
			newEmp.setUserIns(user.getId());

			emSrv.saveNewEmployee(newEmp);
			
			// Initializing field values
			newEmp = null;
			
			// Setting Initialization VAR
			this.setInitVar("S");
			return null;
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());
			log.error(e);
		}finally{
			this.setEmployee(null);
		}
		return "";
	}
	
	// Retrieving data for updating
	public void dataToEdit(Long id) throws CommonException{
		System.out.println("id = " + id.toString());
		for (EmployeeBean bean : this.getAllEmployees()) {
			if(bean.getId() == id){
				this.setEditEmployee(bean);
				this.setPersonCod(convert.getPersonCod(bean.getIdPerson()));
				return;
			}			
		}	
	}
	
	public void dataToEditUpd() throws ParseException{
		try {
			// SETTING EXTERNAL VALUES
			personId = convert.getPersonId(this.getPersonCod());
			personData = convert.getPersonData(this.getPersonCod());
			
			// UPDATING EXTERNAL VALUES
			this.getEditEmployee().setIdPerson(this.getPersonId());
			
			// SAVING VALUES
			EmployeeServices admSrv = new EmployeeServices(this.sqlMap.getConfig());
			admSrv.updateEmployee(this.getEditEmployee());
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO ACTUALIZAR EL REG. " + e.getMessage());
			log.error(e);
		}
	}
	
	public void dataToDelete(Long id){
		for (EmployeeBean bean: this.getAllEmployees()){
			if (bean.getId() == id) {
				try {
					EmployeeServices admSrv  = new EmployeeServices(this.sqlMap.getConfig());
					admSrv.deleteEmployeeById(bean.getId());
					
				} catch (Exception e) {
//					this.facesMessages.add(Severity.ERROR, e.getMessage());
					System.out.println("NO SE BORRAR EL REGISTRO. " + e.getMessage());
					log.error(e);
				}
			}
			
		}
		this.setInitVar("S");
	}

		
	// GETTERS AND SETTERS
	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public boolean isEditMode() {
		return editMode;
	}

	public void setEditMode(boolean editMode) {
		this.editMode = editMode;
	}

	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}

	public EmployeeBean getEmployee() {
		return employee;
	}

	public void setEmployee(EmployeeBean employee) {
		this.employee = employee;
	}

	public Collection<EmployeeBean> getAllEmployees() {
		return allEmployees;
	}

	public void setAllEmployees(Collection<EmployeeBean> allEmployees) {
		this.allEmployees = allEmployees;
	}

	public EmployeeBean getEditEmployee() {
		return editEmployee;
	}

	public void setEditEmployee(EmployeeBean editEmployee) {
		this.editEmployee = editEmployee;
	}

	public PersonBean getPersonCod() {
		return personCod;
	}

	public void setPersonCod(PersonBean personCod) {
		this.personCod = personCod;
	}

	public PersonBean getPersonData() {
		return personData;
	}

	public void setPersonData(PersonBean personData) {
		this.personData = personData;
	}

	public Long getPersonId() {
		return personId;
	}

	public void setPersonId(Long personId) {
		this.personId = personId;
	}

	public UsersBean getUser() {
		return user;
	}

	public void setUser(UsersBean user) {
		this.user = user;
	}
	
	

}
